package luke4fun.wheresmymoney.service.async;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import luke4fun.wheresmymoney.adapter.list.BasicAdapter;
import luke4fun.wheresmymoney.bean.SearchBean;
import luke4fun.wheresmymoney.db.AccDBHelper;
import luke4fun.wheresmymoney.db.DBConstants;
import luke4fun.wheresmymoney.util.FormatUtil;

public class SearchAsyncTask extends AsyncTask<String, Integer, List<SearchBean>> {

	private BasicAdapter<SearchBean> adapter;
	private Context context;
	
	public SearchAsyncTask(Context context, BasicAdapter<SearchBean> adapter) {
		this.context = context;
		this.adapter = adapter;
	}
	
	@Override
	protected List<SearchBean> doInBackground(String... params) {
		String[] args;
		if (params != null && params.length > 0) {
			args = new String[] { "%" + params[0] + "%", 
									"%" + params[0] + "%", 
									"%" + params[0] + "%" };
		} else {
			args = new String[] {"", "", ""};
		}
		
		AccDBHelper dbHelper = new AccDBHelper(context);
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		
		Cursor cursor = db.query(DBConstants.V_RECORD, 
								null, 
								DBConstants.RECORD_CATEGORY + " LIKE ? OR " +
								DBConstants.RECORD_ITEM + " LIKE ? OR " + 
								DBConstants.RECORD_STORE + " LIKE ?", 
								args, 
								null,
								null,
								null);
		
		List<SearchBean> beanList = new ArrayList<SearchBean>();
		while (cursor.moveToNext()) {
			SearchBean bean = new SearchBean();
			long date = cursor.getLong(cursor.getColumnIndex(DBConstants.RECORD_DATATIME));
			String item = cursor.getString(cursor.getColumnIndex(DBConstants.RECORD_ITEM));
			String store = cursor.getString(cursor.getColumnIndex(DBConstants.RECORD_STORE));
			long price = cursor.getLong(cursor.getColumnIndex(DBConstants.RECORD_PRICE));
			String category = cursor.getString(cursor.getColumnIndex(DBConstants.RECORD_CATEGORY));
			
			item = TextUtils.isEmpty(item) ? "" : item;
			store = TextUtils.isEmpty(store) ? "" : store;
			category = TextUtils.isEmpty(category) ? "" : category;
			
			bean.setDate(FormatUtil.formatDateToMMddyyyy(new Date(date)));
			bean.setPrice(String.valueOf(price));
			if (TextUtils.indexOf(item, params[0]) > -1) {
				item += "_@_I";
			}
			bean.setItem(item);
			if (TextUtils.indexOf(store, params[0]) > -1) {
				store += "_@_I";
			}
			bean.setStore(store);
			if (TextUtils.indexOf(category, params[0]) > -1) {
				category += "_@_I";
			}
			bean.setCategory(category);
			
			beanList.add(bean);
		}
		
		cursor.close();
		db.close();
		dbHelper.close();
		
		return beanList;
	}

	@Override
	protected void onPostExecute(List<SearchBean> list) {
		adapter.updateList(list);
	}
}
